package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Override
    public Cart save(Cart cart) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(cart.getDishId()!= null,Cart::getDishId,cart.getDishId());
        wrapper.eq(cart.getSetmealId()!= null,Cart::getSetmealId,cart.getSetmealId());
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        Cart cartFrom = cartMapper.selectOne(wrapper);
        if (cartFrom != null){
            cartFrom.setNumber(cartFrom.getNumber()+1);
            cartMapper.updateById(cartFrom);
            return cartFrom;
        }else {
            cart.setUserId(UserHolder.get().getId());
            cart.setNumber(1);
            cart.setCreateTime(new Date());
            cartMapper.insert(cart);
            return cart;
        }
    }

    @Override
    public List<Cart> cartList() {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId());
        return cartMapper.selectList(wrapper);
    }

    @Override
    public Cart update(Cart cart) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(cart.getDishId()!= null,Cart::getDishId,cart.getDishId());
        wrapper.eq(cart.getSetmealId()!= null,Cart::getSetmealId,cart.getSetmealId());
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        Cart cartFrom = cartMapper.selectOne(wrapper);
        cartFrom.setNumber(cartFrom.getNumber()-1);
        if (cartFrom.getNumber()>0){
            cartMapper.updateById(cartFrom);
            return cartFrom;
        }else{
            cartMapper.deleteById(cartFrom);
            return cartFrom;
        }

    }

    @Override
    public void deleted() {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId());
        cartMapper.delete(wrapper);
    }
}
